package com.junxian.springboot03.juc;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreTest {

    public static void main(String[] args) {

        Semaphore semaphore = new Semaphore(3);

        //抢车位,三个车位，6台车去抢
        for (int i = 1; i <= 100; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    System.out.println(Thread.currentThread().getName() +"进入了停车场，找车等待中");
                    semaphore.acquire();//获取车位
                    System.out.println(Thread.currentThread().getName() +"获取车位：" + finalI);
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();//释放车位
                    System.out.println(Thread.currentThread().getName() + "办完事情了，释放车位：" + finalI);
                }
            }, "车主" +String.valueOf(i)).start();
        }

    }

}
